const Router = require('koa-router')
const router = new Router({
    prefix: '/v1/token'
});
const { loginType } = require('../../lib/enum')
const { TokenValidator } = require('../../validators/validator')
const { User } = require('../../models/user')
const { ParameterException } = require('../../../core/httpException')
const { generateToken } = require('../../../core/util')
const { Auth } = require('../../../middlewares/auth')
const { WXManager } = require('../../services/wx')
const { NotEmpty } = require('../../validators/validator')
router.post('/', async (ctx,next)=>{
    const v = await new TokenValidator().validate(ctx)
    // 根据type进行不同的处理
    // API有些是公开api  有些不是公开api

    let token;
    switch (v.get('body.type')){
        case loginType.user_email:
            token = await emailLogin(v.get('body.account'),v.get('body.secret'))
            break;
        case loginType.user_mini_program:
            token = await WXManager.codeToToken(v.get('body.account'))
            break;
        default:
            throw new ParameterException(['登陆类型无处理函数'])
    }
    ctx.body = {
        token
    }
})

router.post('/verify',async ctx=>{
    const v = await new NotEmpty().validate(ctx);
    const result = Auth.verifyToken(v.get('body.token'))
    ctx.body={
        result
    }
})


const emailLogin = async (account, secret) =>{
    const user = await User.verifyEmailPassword(account,secret)
    return generateToken(user.id,Auth.USER)
}

module.exports = router;